using System.Security.Claims;
using AutoMapper;
using Core.Db.Dtos;
using Core.Db.Helper;
using Core.Db.Models;
using Core.Db.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Core.API.Controllers;

[ApiController]
[Route("api/shoppingCart")]
public class ShoppingCartController : ControllerBase
{
    private readonly ITouristRouteRepository _touristRouteRepository;
    private readonly IMapper _mapper;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ShoppingCartController(ITouristRouteRepository touristRouteRepository, IMapper mapper, IHttpContextAccessor httpContextAccessor)
    {
        _touristRouteRepository = touristRouteRepository;
        _mapper = mapper;
        _httpContextAccessor = httpContextAccessor;
    }


    [Authorize]
    [HttpGet]
    public async Task<IActionResult> GetShoppingCart()
    {
        // 1. 获取当前用户
        var userId = _httpContextAccessor
            .HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        // 2. 使用userid 获得购物车
        var shoppingCart = await _touristRouteRepository.GetShoppingCartByUserId(userId);

        return Ok(_mapper.Map<ShoppingCartDto>(shoppingCart));
    }

    [Authorize(AuthenticationSchemes = "Bearer")]
    [HttpPost("items")]
    public async Task<IActionResult> AddShoppingCartItem([FromBody] AddShoppingCartItemDto addShoppingCartItemDto)
    {
        // 1. 获取当前用户
        var userId = _httpContextAccessor
            .HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        // 2. 使用userid 获得购物车
        var shoppingCart = await _touristRouteRepository.GetShoppingCartByUserId(userId);

        // 3. 创建 LineItem
        var touristRoute = await _touristRouteRepository.GetTouristRouteAsync(addShoppingCartItemDto.TouristRouteId);

        if (touristRoute == null)
        {
            return NotFound("旅游路线不存在");
        }

        var lineItem = new LineItem()
        {
            TouristRouteId = addShoppingCartItemDto.TouristRouteId,
            ShoppingCartId = shoppingCart.Id,
            OriginalPrice = touristRoute.OriginalPrice,
            DiscountPresent = touristRoute.DiscountPresent
        };

        // 4. 添加 lineItem 并保存数据库
        await _touristRouteRepository.AddShoppingCartItem(lineItem);
        await _touristRouteRepository.SaveAsync();
        return Ok(_mapper.Map<ShoppingCartDto>(shoppingCart));
    }

    [Authorize(AuthenticationSchemes = "Bearer")]
    [HttpDelete("items/{itemId}")]
    public async Task<IActionResult> DeleteShoppingCartItem([FromRoute] int itemId)
    {
        var lineItem = await _touristRouteRepository.GetShoppingCartItemByItemId(itemId);
        if (lineItem == null)
        {
            return NotFound("购物车商品未找到！");
        }

        await _touristRouteRepository.DeleteShoppingCartItem(lineItem);
        await _touristRouteRepository.SaveAsync();

        return NoContent();
    }

    [Authorize(AuthenticationSchemes = "Bearer")]
    [HttpDelete("items/({itemIDs})")]
    public async Task<IActionResult> DeleteSHoppingCartItems([ModelBinder(BinderType = typeof(ArrayModelBinder))] [FromRoute] IEnumerable<int> itemIDs)
    {
        var lineItems = await _touristRouteRepository.GetShoppingCartsByIdListAsync(itemIDs);
        await _touristRouteRepository.DeleteShoppingCartItems(lineItems);
        await _touristRouteRepository.SaveAsync();
        return NoContent();
    }

    [Authorize(AuthenticationSchemes = "Bearer")]
    [HttpPost("checkout")]
    public async Task<IActionResult> Checkout()
    {
        // 1. 获取当前用户
        var userId = _httpContextAccessor
            .HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        // 2. 使用userid 获得购物车
        var shoppingCart = await _touristRouteRepository.GetShoppingCartByUserId(userId);

        // 3. 创建订单
        var order = new Order()
        {
            Id = Guid.NewGuid(),
            UserId = userId,
            State = OrderStateEnum.Pending,
            OrderItems = shoppingCart.ShoppingCartItems,
            CreateDateUTC = DateTime.UtcNow,
            TransactionMetadata = "",
        };
        shoppingCart.ShoppingCartItems = null;

        // 4. 保存数据
        await _touristRouteRepository.AddOrderAsync(order);
        await _touristRouteRepository.SaveAsync();

        return Ok(_mapper.Map<OrderDto>(order));
    }
}